import os
from typing import TypedDict, Annotated
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.constants import START, END
from langgraph.graph import add_messages, StateGraph
from langgraph.prebuilt import ToolNode
import requests
import json

# 使用DeepSeek-chat模型作为chatmodel
modelDS = ChatOpenAI(model="deepseek-chat",
                   api_key=os.environ.get("DEEPSEEK_API_KEY"),
                   base_url=os.environ.get("DEEPSEEK_BASE_URL"))

modelZP = ChatOpenAI(model="glm-4-flash",
                   api_key="0d28f030249b4fe38dc501510748b595.9SGm9tuJBlcgqKBm",
                   base_url="https://open.bigmodel.cn/api/paas/v4/")

@tool
def fetch_real_time_info(query):
    """Get real-time Internet information"""

    url = "https://google.serper.dev/search"

    payload = json.dumps({
        "q": query,
        "num": 3,
    })

    headers = {
        'X-API-KEY': 'd9c2c002085468d95712cbc71d76c4302b4f7342',
        'Content-Type': 'application/json'
    }

    response = requests.post(url, headers=headers, data=payload)

    data = json.loads(response.text)  # 将返回的JSON字符串转换为字典
    if 'organic' in data:
        return json.dumps(data['organic'], ensure_ascii=False)  # 返回'organic'部分的JSON字符串
    else:
        return json.dumps({"error": "No organic results found"}, ensure_ascii=False)  # 如果没有'organic'键，返回错误信息


@tool
def get_weather(location):
    """Call to get the current weather."""
    if location.lower() in ["beijing","北京"]:
        return "北京的温度是16度，天气晴朗。"
    elif location.lower() in ["shanghai","上海"]:
        return "上海的温度是20度，部分多云。"
    else:
        return "不好意思，并未查询到具体的天气信息。"


tools = [fetch_real_time_info, get_weather]

tool_node = ToolNode(tools)

# model_with_tools = modelDS.bind_tools(tools)
model_with_tools = modelZP.bind_tools(tools)

print(tool_node.invoke({"messages":[model_with_tools.invoke("DeepSeek v3 最新的新闻")]}))
print(tool_node.invoke({"messages":[model_with_tools.invoke("北京气温怎么样？")]}))